﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShareRss.Dll
{
    public class TxtIO
    {
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="name">文本名称</param>
        /// <param name="path">路径</param>
        /// <param name="isAdd">是否为追加文字，false为新建文件</param>
        public static void Write(string txt, string name, string path = "")
        {
            FileStream fs = null;
            NewFolder(path);
            var newPath = $"{path}/{name}.txt";
            if (!File.Exists(path))
            {
                fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);//创建写入文件
            }
            else
            {
                fs = new FileStream(newPath, FileMode.Open, FileAccess.Write);
            }
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            sw.WriteLine(txt);//开始写入值
            sw.Close();
            fs.Close();
        }


        /// <summary>
        /// 读
        /// </summary>
        /// <param name="path"></param>
        public static string Read(string name, string path)
        {
            try
            {
                string newPath = $"{path}/{name}.txt";
                StreamReader sr = new StreamReader(newPath, Encoding.UTF8);
                String line;
                string txt = string.Empty;
                while ((line = sr.ReadLine()) != null)
                {
                    txt += line.ToString();
                }
                sr.Close();
                return txt;
            }
            catch (IOException e)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="txt"></param>
        public static void Delete(string path)
        {
            FileAttributes attr = File.GetAttributes(path);
            if (attr == FileAttributes.Directory)
            {
                Directory.Delete(path, true);
            }
            else
            {
                File.Delete(path);
            }
        }

        public static void NewFolder(string path)
        {
            if (!Directory.Exists(path))//若文件夹不存在则新建文件夹   
            {
                Directory.CreateDirectory(path); //新建文件夹   
            }
        }
    }
}
